package edu.ptu.acl.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import edu.ptu.acl.common.MyConstants;
import edu.ptu.acl.dto.TokenPayload;

import java.util.Calendar;
import java.util.HashMap;

public class JWTUtil {

    private static String privateKey = MyConstants.Jwt.PRIVATE_KEY.getValue();

    public static String getToken(Long userId,Long snowId){
        // 指定token过期时间为12小时
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, 12);
        String token = JWT
                .create()
                .withHeader(new HashMap<>())  // Header
                .withClaim("userId" ,userId)// Payload
                .withClaim("snowId",snowId)
                .withExpiresAt(calendar.getTime())  // 过期时间
                .sign(Algorithm.HMAC256(privateKey));// 签名用的secret
        return token;
    }

    public static TokenPayload parseToken(String token){

        // 创建解析对象，使用的算法和secret要与创建token时保持一致
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(privateKey)).build();
        // 解析指定的token
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        // 获取解析后的token中的payload信息
        Claim userId = decodedJWT.getClaim("userId");
        Claim snowId = decodedJWT.getClaim("snowId");

        TokenPayload tokenPayload = TokenPayload.builder().userId(userId.asLong())
                .snowId(snowId.asLong()).build();

        return tokenPayload;

    }

}
